/**
 * Created by guoqs on 2018/5/15.
 */
export class ScriptLoader {
  _scripts = {}
  constructor (script) {
    this._scripts[script.name] = {
      src: script.src,
      loaded: false
    }
  }

  load (...scripts) {
    const promise = []
    scripts.forEach((script) => {
      promise.push(this.loadScripts(script))
    })
    return Promise.all(promise)
  }

  loadScripts (name) {
    return new Promise((resolve, reject) => {
      if (this._scripts[name].loaded) {
        resolve({script: name, loaded: true, status: `Already loaded script：${name}`})
      } else {
        const script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = this._scripts[name].src
        script.onload = () => {
          this._scripts[name].loaded = true
          resolve({script: name, loaded: true, status: `loaded`})
        }
        script.onerror = () => resolve({script: name, loaded: false, status: 'loaded'})
        document.getElementsByTagName('head')[0].appendChild(script)
      }
    })
  }
}
